<template>
  <div class="wrap">
    <div id="container">
      <!-- 定义一个表格元素 -->
      <!--<button id="redraw">更换数据源</button>-->
      <section class="detail-header">
        <div class="col-sm-12 console-title">
          <h5 class="">告警联系人管 理</h5>
          <div class="stayRight ">
            <el-button @click="refresh()" icon="star-off">刷新</el-button>
            <el-button type="primary" @click="showMonitor()">{{createButtonLabel}}</el-button>
          </div>
        </div>
      </section>
      <section class="detail-header">
        <el-tabs v-model="tagActiveName" type="card" @tab-click="handleTagClick">
          <el-tab-pane label="告警联系人" name="alarmContacts">
              <section class="searchBar">
                <div class="form-inline">
                  <div class="pull-left">
                    <div class="searchIpt">
                      <el-input v-model="searchStr" placeholder="请输入要查询联系人的姓名、手机号码、或者Email"></el-input>
                    </div>
                    <div class="searchbtn">
                      <el-button @click="alarmContactsList(1,searchStr,10)">搜索</el-button>
                    </div>
                  </div>
                </div>
              </section>
              <section class="tableMain">
                <el-table :data="dataArr" border style="width: 100%" @selection-change="handleSelectionChange">
                  <el-table-column type="selection" width="55"></el-table-column>
                  <el-table-column prop="name" label="姓名"> </el-table-column>
                  <el-table-column prop="mobile" label="手机号"> </el-table-column>
                  <el-table-column prop="email" label="邮箱"> </el-table-column>
                  <el-table-column label="操作">
                    <template scope="scope">
                      <el-button size="small" type="text" @click="showMonitor(scope.$index, dataArr)">编辑</el-button> |
                      <el-button size="small" type="text" @click="deleteAlarmContacts(scope.$index, dataArr)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="pageSIzeblock">
                  <div class="pullright">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagesz" layout="total, sizes, prev, pager, next, jumper" :total="totalSize">
                    </el-pagination>
                  </div>
                  <div class="pullLeft">
                    <el-button size="small" name="button-del" @click="addToGroup()" :disabled="pdisabled">添加到告警联系人组</el-button>
                    <el-button size="small" name="button-del" @click="delAll()" :disabled="pdisabled">批量删除联系人</el-button>
                  </div>
                </div>
              </section>
          </el-tab-pane>
          <el-tab-pane label="告警联系组" name="alarmContactsGroup">
            <div v-if="alarmContactsGroupList.length < 1" style="border:1px solid #dfe6ec;text-align:center;height:50px;padding-top:30px;">无告警联系组</div>
            <div style="position:relative;" v-for="(item,index) in alarmContactsGroupList" :key="index">
              <div class="panel-top-icon" style="right: 0px; height: 45px;  width:45px; top: 0px;" @click="deleteContactsGroup(item.id)">
                <i class="el-icon-delete" style="padding-top: 15px;"></i>
              </div>
              <div class="panel-top-icon" style="right: 40px; height: 45px; width:45px; top: 0px;" @click="showMonitor(0, item)">
                <i class="el-icon-edit" style="padding-top: 15px;"></i>
              </div>
              <el-collapse v-if="index==0">
                <el-collapse-item name="1">
                  <template slot="title">
                    <strong>{{item.name}} &nbsp; &nbsp; &nbsp; <span style="color:red;">({{item.contactsList.length}}个联系人)</span></strong>
                  </template>
                  <div v-for="(item2,index2) in item.contactsList" :key="index2">
                    <div style="float:left;width:25%;">{{item2.name}}</div>
                    <div style="float:left;width:25%;">{{item2.mobile}}</div>
                    <div style="float:left;width:25%;">{{item2.email}}</div>
                    <div style="float:right;width:25%;">
                      <el-button size="small" type="text" v-if="item.contactsList.length>1" @click="deleteContactsGroupRef(item.id, index2 , item.contactsList)" >删除</el-button>
                    </div>
                  </div>
                  <!-- <el-table :data="item.contactsList" border style="width: 100%">
                    <el-table-column prop="name" label="姓名" width="400px"></el-table-column>
                    <el-table-column prop="mobile" label="手机号码" width="400px"></el-table-column>
                    <el-table-column prop="email" label="邮箱" width="400px"></el-table-column>
                    <el-table-column label="操作" width="300px">
                      <template scope="scope">
                        <el-button size="small" type="text" v-if="item.contactsList.length>1" @click="deleteContactsGroupRef(item.id, scope.$index, item.contactsList)" >删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table> -->
                </el-collapse-item>
              </el-collapse>
              <el-collapse v-if="index!=0" style="border-top:0px;">
                <el-collapse-item name="1">
                  <template slot="title">
                    <strong>{{item.name}} &nbsp; &nbsp; &nbsp; <span style="color:red;">({{item.contactsList.length}}个联系人)</span></strong>
                  </template>
                  <div v-for="(item2,index2) in item.contactsList" :key="index2">
                    <div style="float:left;width:25%;">{{item2.name}}</div>
                    <div style="float:left;width:25%;">{{item2.mobile}}</div>
                    <div style="float:left;width:25%;">{{item2.email}}</div>
                    <div style="float:right;width:25%;">
                      <el-button size="small" type="text" v-if="item.contactsList.length>1" @click="deleteContactsGroupRef(item.id, index2 , item.contactsList)" >删除</el-button>
                    </div>
                  </div>
                  <!-- <el-table :data="item.contactsList" border style="width: 100%">
                    <el-table-column prop="name" label="姓名" width="50"></el-table-column>
                    <el-table-column prop="mobile" label="手机号码" width="50"></el-table-column>
                    <el-table-column prop="email" label="邮箱" width="50"></el-table-column>
                    <el-table-column label="操作" width="50">
                      <template scope="scope">
                        <el-button size="small" type="text" v-if="item.contactsList.length>1" @click="deleteContactsGroupRef(item.id, scope.$index, item.contactsList)" >删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table> -->
                </el-collapse-item>
              </el-collapse>
            </div>       
          </el-tab-pane>
        </el-tabs>
      </section>
      <el-dialog :title="alarmContactsTitle" :visible.sync="creatDialogVislble" class="customDialog team" :lock-scroll="false">
        <div class="scoreContainer tagCategory">
          <el-form :model="alarmContactsForm" :rules="rules" ref="alarmContactsForm" label-width="120px" class="demo-alarmContactsForm">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="alarmContactsForm.name"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="alarmContactsForm.mobile"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="alarmContactsForm.email"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="creatDialogVislble = false">取 消</el-button>
          <el-button type="primary" @click="saveAlarmContacts('alarmContactsForm')">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog :title="alarmContactsGroupTitle" :visible.sync="alarmGroupdialog" :lock-scroll="false">
        <div class="scoreContainer tagCategory">
          <el-form :model="alarmContactsGroupForm" :rules="groupRules" ref="alarmContactsGroupForm" label-width="120px" class="demo-alarmContactsGroupForm">
            <el-form-item label="组名" prop="name">
              <el-input v-model="alarmContactsGroupForm.name"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="description">
              <el-input v-model="alarmContactsGroupForm.description"></el-input>
            </el-form-item>
            <el-form-item label="选择联系人" prop="transfer">
                <el-transfer 
                  filterable
                 :footer-format="{
                    noChecked: '共${total}项',
                    hasChecked: '已选${checked}/${total} 项'
                  }"
                 :titles="['未选联系人', '已选联系人']"  
                 v-model="alarmContactsGroupForm.contactIds" 
                 :data="AlarmContactData"> 
                </el-transfer>
            </el-form-item>
          </el-form>
        </div>  
        <span slot="footer" class="dialog-footer">
          <el-button @click="alarmGroupdialog = false" >取 消</el-button>
          <el-button type="primary" @click="saveAlarmContactsGroup('alarmContactsGroupForm')">确 定</el-button>
        </span> 
      </el-dialog>
      
      <el-dialog title="添加到告警联系人组" :visible.sync="addToGroupVislble" :lock-scroll="false">
          <div class="scoreContainer tagCategory" style="height:350px;overflow:auto;">
            <el-form :model="addToGroupForm" :rules="rules" ref="addToGroupForm" label-width="120px" class="demo-addToGroupForm">
              <el-form-item label="选择联系人组" prop="contactsGroups">
                <el-checkbox-group v-model="addToGroupForm.contactsGroups">
                  <el-checkbox v-for="item in alarmContactsGroupList" :key="item.id" :label=item.id  name="contactsGroups" >{{item.name}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addToGroupVislble = false">取 消</el-button>
            <el-button type="primary" @click="addToGroupSubmit('addToGroupForm')">确 定</el-button>
          </span>
      </el-dialog>

      
    </div>
  </div>
</template>
<script>
import Agroup from '@/views/components/alarmGroup'
import { getAlarmContactsList, deleteAlarmContactsById, getAlarmContactsGroupList, modifyAlarmContacts, deleteAlarmContactsByIds, contactsAddToGroup, deleteAlarmContactsGroupRef, deleteAlarmContactsGroup, getAlarmContactsAllList, modifyAlarmContactsGroup } from '@/api/alarmRulesData'
export default {
  components: {
    Agroup
  },
  data() {
    return {
      test: [1, 19],
      tagActiveName: 'alarmContacts', //  点击tag标记
      searchStr: '',  //  搜索字段
      createButtonLabel: '新建联系人', //  新建按钮label
      dataArr: null,
      alarmContactsTitle: '', //  创建联系人弹出框title
      dataAddress: [],
      listLoading: true,
      isNotPermission: '',
      advancedSettings: false,
      pdisabled: true,
      creatDialogVislble: false,
      addToGroupVislble: false,
      currentSetting: '',
      currentPage: 1,
      pagesz: 10,
      totalSize: 0,
      hasError: false,
      selected: '',
      tpvalue: '',
      multipleSelection: [],
      alarmContactsGroupList: [],
      addToGroupForm: {
        contactsGroups: []
      },
      alarmContactsForm: {
        name: '',
        mobile: '',
        email: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change' }
        ],
        contactsGroups: [
          { type: 'array', required: true, message: '请至少选择一个联系人组', trigger: 'change' }
        ]
      },
      //  联系人组
      alarmContactsGroupTitle: '', //  创建联系人组弹出框title
      alarmGroupdialog: false,
      AlarmContactData: [], //  生成联系人组管理
      alarmContactsGroupForm: {
        name: '',
        description: '',
        contactIds: []
      },
      groupRules: {
        name: [
          { required: true, message: '请输入组名', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      },
      isOpen: false
    }
  },
  created() {
    this.alarmContactsList(1)
  },
  methods: {
    alarmContactsList(curr, searchStr, size) {
      this.listLoading = true
      if (size === undefined) {
        size = 10
      }
      var listQuery = { currPage: curr, searchStr: searchStr, pageSize: size }
      getAlarmContactsList(listQuery).then(response => {
        this.dataArr = response.data.data
        this.listLoading = false
        this.totalSize = response.data.totalRows
        this.currentPage = curr
        this.pagesz = size
      })
    },
    alarmGroupList() {
      this.listLoading = true
      getAlarmContactsGroupList().then(response => {
        this.listLoading = false
        this.alarmContactsGroupList = response.data.data
      })
    },
    //  刷新按钮事件
    refresh() {
      if (this.tagActiveName === 'alarmContacts') {
        this.alarmContactsList(1)
      } else {
        this.alarmGroupList()
      }
    },
    //  创建编辑联系人/联系人组
    showMonitor(index, data) {
      if (this.tagActiveName === 'alarmContacts') {
        //  编辑管理联系人
        this.creatDialogVislble = true
        if (data !== undefined) {
          this.alarmContactsTitle = '修改告警联系人'
          this.alarmContactsForm = {
            id: data[index].id,
            name: data[index].name,
            mobile: data[index].mobile,
            email: data[index].email
          }
        } else {
          this.alarmContactsTitle = '创建告警联系人'
          this.alarmContactsForm = {
            name: '',
            mobile: '',
            email: ''
          }
        }
      } else {
        getAlarmContactsAllList().then(response => {
          if (response.data.code === 0) {
            this.AlarmContactData = []
            response.data.data.forEach(function(element) {
              this.AlarmContactData.push({
                key: element.id,
                label: element.name
              })
            }, this)
          }
        })
        //  编辑管理联系人组
        if (data !== undefined) {
          this.alarmContactsGroupTitle = '修改联系人组'
          const contactIds = []
          data.contactsList.forEach(function(element) {
            contactIds.push(element.id)
          }, this)
          this.alarmContactsGroupForm = {
            id: data.id,
            name: data.name,
            description: data.description,
            contactIds: contactIds
          }
        } else {
          this.alarmContactsGroupForm = {
            name: '',
            description: '',
            contactIds: []
          }
          this.alarmContactsGroupTitle = '创建联系人组'
        }
        this.alarmGroupList()
        this.alarmGroupdialog = true
      }
    },
    //  保存联系人
    saveAlarmContacts(formName) {
      const _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('确认保存联系人？', '提示', {
            type: 'warning'
          })
          .then(_ => {
            modifyAlarmContacts(this.alarmContactsForm).then(response => {
              if (response.data.code === 0) {
                _this.creatDialogVislble = false
                _this.alarmContactsList(1)
                _this.$message({
                  message: '操作成功!',
                  type: 'success'
                })
              } else {
                _this.$message({
                  message: response.data.msg,
                  type: 'warning'
                })
              }
            })
          })
          .catch(_ => {})
          console.log(this.templetForm, 'templetForm')
        }
      })
    },
    //  保存联系人组
    saveAlarmContactsGroup(formName) {
      const _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('确认保存联系组？', '提示', {
            type: 'warning'
          })
          .then(_ => {
            modifyAlarmContactsGroup(this.alarmContactsGroupForm).then(response => {
              if (response.data.code === 0) {
                _this.alarmGroupdialog = false
                _this.alarmGroupList()
                _this.$message({
                  message: '操作成功!',
                  type: 'success'
                })
              } else {
                _this.$message({
                  message: response.data.msg,
                  type: 'warning'
                })
              }
            })
          })
          .catch(_ => {})
          console.log(this.templetForm, 'templetForm')
        }
      })
    },
    handleSizeChange(val) {
      this.alarmContactsList(1, '', val)
    },
    handleCurrentChange(val) {
      this.alarmContactsList(val)
    },
    addToGroup() {
      this.alarmGroupList()
      this.addToGroupVislble = true
      //  this.addToGroupForm.contactsGroups = [2, 1]
    },
    addToGroupSubmit(formName) {
      const _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('确认添加到告警联系组？', '提示', {
            type: 'warning'
          })
          .then(_ => {
            const alarmContactIds = []
            this.multipleSelection.forEach(function(element) {
              alarmContactIds.push(element.id)
            }, this)
            const contactsAddToGroupObj = {
              alarmContactIds: alarmContactIds.join(','),
              alarmContactGroupIds: this.addToGroupForm.contactsGroups.join(',')
            }
            contactsAddToGroup(contactsAddToGroupObj).then(response => {
              if (response.data.code === 0) {
                _this.addToGroupVislble = false
                this.$refs[formName].resetFields()
                _this.alarmContactsList(1)
                _this.$message({
                  message: '操作成功!',
                  type: 'success'
                })
              }
            })
          })
          .catch(_ => {})
        }
      })
    },
    deleteAlarmContacts(index, data) {
      this.$confirm('确认删除告警联系人？', '提示', {
        type: 'warning'
      })
      .then(_ => {
        const alarmContactsId = data[index].id
        deleteAlarmContactsById(alarmContactsId).then(response => {
          if (response.data.code === 0) {
            this.alarmContactsList(1)
            this.$message({
              message: '删除成功!',
              type: 'success'
            })
          }
        })
      })
      .catch(_ => {})
    },
    deleteContactsGroupRef(group_id, index, data) {
      this.$confirm('确认将该用户从组中删除？', '提示', {
        type: 'warning'
      })
      .then(_ => {
        const obj = {
          alarmContactId: data[index].id,
          alarmContactGroupId: group_id
        }
        deleteAlarmContactsGroupRef(obj).then(response => {
          if (response.data.code === 0) {
            this.alarmGroupList()
            this.$message({
              message: '操作成功!',
              type: 'success'
            })
          }
        })
      })
      .catch(_ => {})
    },
    deleteContactsGroup(group_id) {
      this.$confirm('确认删除该用户组？', '提示', {
        type: 'warning'
      })
      .then(_ => {
        deleteAlarmContactsGroup(group_id).then(response => {
          if (response.data.code === 0) {
            this.alarmGroupList()
            this.$message({
              message: '删除成功!',
              type: 'success'
            })
          }
        })
      })
      .catch(_ => {})
    },
    //  删除多个联系人
    delAll() {
      this.$confirm('确认删除告警联系人？', '提示', {
        type: 'warning'
      })
      .then(_ => {
        const idQuery = []
        this.multipleSelection.forEach(function(element) {
          idQuery.push(element.id)
        }, this)
        const obj = {
          ids: idQuery.join(',')
        }
        deleteAlarmContactsByIds(obj).then(response => {
          if (response.data.code === 0) {
            this.alarmContactsList(1)
            this.$message({
              message: '删除成功!',
              type: 'success'
            })
          }
        })
      })
      .catch(_ => {})
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      if (this.multipleSelection.length > 0) {
        this.pdisabled = false
      } else {
        this.pdisabled = true
      }
      console.log(this.multipleSelection, 'multipleSelection')
    },
    handleTagClick(tab, event) {
      console.log(tab, this.tagActiveName)
      if (this.tagActiveName === 'alarmContacts') {
        this.createButtonLabel = '新建联系人'
      } else {
        this.createButtonLabel = '新建联系组'
        this.alarmGroupList()
      }
    },
    handFlex() {
      this.isOpen = !this.isOpen
    }
  }
}

</script>
<style lang="scss">
.detail-header {
  padding: 0 15px;
  margin-bottom: 10px;
  overflow: hidden;
  .console-title {
    padding: 16px 0px;
    min-height: 70px;
    border-bottom: 1px solid #eee;
    position: relative;
    h5 {
      display: inline-block;
      text-indent: 8px;
      border-left: 2px solid #88B7E0;
      margin: 8px 0;
      margin-right: 8px;
      vertical-align: top;
    }
    .stayRight {
      position: absolute;
      top: 15px;
      right: 0;
      overflow: hidden;
      .refresh {
        float: left;
        margin-right: 10px;
        color: #333;
        border: 1px solid #ddd;
        background-color: #F7F7F7;
      }
      .creatSite {
        float: left;
      }
    }
  }
}

.searchSel {
  width: 150px;
  display: inline-block;
}

.searchIpt {
  width: 350px;
  display: inline-block;
}

.searchbtn {
  width: 100px;
  display: inline-block;
}

.searchBar {
  padding: 0 10px;
}

.tableMain {
  padding: 10px;
}

.typeform {
  display: inline;
  .form-control {
    border: none;
    padding: 0;
    box-shadow: none;
    display: inline;
    height: 30px;
    width: 60%;
  }
}

.spantype {
  display: inline;
}

.pageSIzeblock {
  overflow: hidden;
  padding: 10px 0;
  .pullright {
    float: right;
  }
}
.statusError {
  color: red;
}
.panel-top-icon {
  display: inline-block;
  border-left: 1px solid #e1e6eb;
  width: 40px;
  text-align: center;
  cursor: pointer;
  position: absolute;
  font-size: 13px;
}
</style>